import time
import hmac
import hashlib
import base64
import json
import urllib.parse
import urllib.request
from datetime import datetime


class DingDingWebHook(object):
    def __init__(self, secret=None, url=None):
        """
        :param secret: 安全设置的加签秘钥
        :param url: 机器人没有加签的WebHook_url
        """
        if secret is not None:
            secret = secret
        else:
            secret = 'SEC960983a0d1100d410ce442cb5ceb748fd5e2fe54bc43d911e9ed67461a067f3e'  # 加签秘钥
        if url is not None:
            url = url
        else:
            url = "https://oapi.dingtalk.com/robot/send?access_token=e496f742b0e66f7ea4ac8c4c660e9b29694ac3ca70ab0650dcb2e65e2476c317"  # 无加密的url

        timestamp = round(time.time() * 1000)  # 时间戳
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))  # 最终签名

        self.webhook_url = url + '&timestamp={}&sign={}'.format(timestamp, sign)  # 最终url，url+时间戳+签名

    def send_meassage(self, testcase_num=None, pass_num=None, fail_num=None, elapsed_ms=None, version=None, report_url=None):
        """
        发送消息至机器人对应的群
        :param data: 发送的内容
        :return:
        """
        data = {
            "msgtype": "markdown",
            "markdown": {"title": "接口自动化报告",
                         "text": "# 接口运行运行报告 \n\n " +
                                 "\n{0}".format(format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) +
                                 "\n- 用例数量：{0}".format(testcase_num) +
                                 "\n- 成功数量：{0}".format(pass_num) +
                                 "\n- 失败数量：{0}".format(fail_num) +
                                 "\n- 执行时长：{0}".format(elapsed_ms) +
                                 "\n- 执行版本：{0}".format(version) +
                                 "\n- [报告详情]({0})".format(report_url)
                         },
            "at": {
                "atMobiles": [18688889999],
                "isAtAll": False}  # 是否@所有人
        }
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        send_data = json.dumps(data)  # 将字典类型数据转化为json格式
        send_data = send_data.encode("utf-8")  # 编码为UTF-8格式
        request = urllib.request.Request(url=self.webhook_url, data=send_data, headers=header)  # 发送请求

        opener = urllib.request.urlopen(request)  # 将请求发回的数据构建成为文件格式
        print(opener.read())  # 打印返回的结果
